<?php

namespace App\V3\V3_2_6\Controllers;

use App\V3\V3_2_6\Models\LogInStorageModel;
use App\V3\V3_2_6\Models\LogOutStorageModel;
use App\V3\V3_2_6\Models\LogPackageModel;
use App\V3\V3_2_6\Models\MaterielModel;
use App\V3\V3_2_6\Models\OverflowBreakageModel;
use App\V3\V3_2_6\Models\ProductOrderModel;
use App\V3\V3_2_6\Models\SalesReturnModel;
use App\V3\V3_2_6\Models\SellModel;
use App\V3\V3_2_6\Models\StorageManageModel;
use App\V3\V3_2_6\Models\SupplierCustomerModel;
use App\V3\V3_2_6\Models\TallyClassModel;
use App\V3\V3_2_6\Models\TallyModel;
use App\V3\V3_2_6\Services\StatisticsService;
use App\Helper\Utils\TimeUtil;
use App\V3\V3_2_6\Models\MaterielContentModel;
use App\V3\V3_2_6\Models\SellGoodsDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\V3\V3_2_6\Models\ExpressModel;

class StatisticsController extends BaseController
{
    /**
     * 已销售统计
     * change 在 2021/11/11 16:35 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sell(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type' =>'required|integer',//时间 1-今日 2-本月 3-本季
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $condition[] = ['main_id','=',$this->getMainUserId()];
        $condition[] = ['out_status','=',1];
        $condition[] = ['pay_status','=',1];
        $condition[] = ['repeal_status','=',0];

        if($data['type']==1){
            $date = TimeUtil::convertDateSignToUnix();
        }elseif($data['type']==2){
            $date = TimeUtil::convertDateSignToUnix('month');
        }elseif($data['type']==3){
            $date = $this->quarter();
        }
        $tallyModel = SellGoodsDetail::select(DB::raw("sum(num) as num,image,name,sum((price-cost_price)*num) as profit,sum(price*num) as total_price"))
            ->where($condition)
            ->whereBetween('sell_date',$date)
            ->groupBy('name','type_name')->get();
//        $modelData['data'] = $tallyModel;
//        $modelData['total_piece'] = SellGoodsDetail::where($condition)
//            ->whereBetween('created_at',$date)
//            ->sum('piece');
        $totalMoney = 0;
        $totalNum = 0;
        foreach ($tallyModel as $value){
            $totalMoney+=$value['total_price'];
            $totalNum += $value['num'];
        }
        $modelData['data'] = SellGoodsDetail::select(DB::raw("sum(num) as num,image,name,type_name,materiel_no,sum((price-cost_price)*num) as profit,sum(price*num) as total_price"))
            ->where($condition)
            ->whereBetween('sell_date',$date)
            ->groupBy('name','type_name')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
        $modelData['total_num'] = $totalNum;
        $modelData['total_money'] = $totalMoney;//总销售额
        return $this->success($modelData);
    }

    /**
     * 当前季度
     * change 在 2021/11/12 10:55 创建
     * @return array
     */
    public function quarter(){
        $moth =  (int)date('m');
        if(in_array($moth,[1,2,3])){
            $startDate = strtotime(date('Y').'-01');
            $endDate = strtotime(date('Y').'-03-31 23:59:59');
        }elseif (in_array($moth,[4,5,6])){
            $startDate = strtotime(date('Y').'-04');
            $endDate = strtotime(date('Y').'-06-30 23:59:59');
        }elseif (in_array($moth,[7,8,9])){
            $startDate = strtotime(date('Y').'-07');
            $endDate = strtotime(date('Y').'-09-30 23:59:59');
        }elseif (in_array($moth,[10,11,12])){
            $startDate = strtotime(date('Y').'-10');
            $endDate = strtotime(date('Y').'-12-31 23:59:59');
        }
        return [$startDate, $endDate];
    }

    /**
     * 收入
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/6 16:07
     * @return \Illuminate\Http\JsonResponse
     */
    public function incomeOrExpend(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
            'type' =>[
                'required',
                Rule::In([0,1]),
            ],//收支类型：0-收入 1-支出
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：'.date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：'.date('Y-m-d'),
            'type.required' => '`报表类型`缺失',
            'type.in' => '`报表类型`错误',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        $condition = [];

        if(!empty($startTime) && !empty($endTime)) {
            $condition[] = ['add_time', '>=', $startTime];
            $condition[] = ['add_time', '<=', $endTime];
        }
        else if(!empty($startTime) && empty($endTime)) {
            $condition[] = ['add_time', '>=', $startTime];
        }
        else if(empty($startTime) && !empty($endTime)) {
            $condition[] = ['add_time', '<=', $endTime];
        }

        $condition['type'] = ['EQ' => $data['type']];

        $condition['main_id'] = ['EQ' => $this->getMainUserId()];

        $totalInfo = TallyModel::selectRaw(
            'SUM(money) as money'
        )->where($condition);

        $incomeList = TallyModel::selectRaw(
            'add_time,money,tally_class_name'
        )->where($condition);

        $tallyClassId = [];
        if(isset($data['tally_class_id'])) {
            $tallyClassInfo = TallyClassModel::where('id', $data['tally_class_id'])->first();

            if($tallyClassInfo['parent_id'] == 0) {
                //获取二级几张类型信息
                $getTallyClass = TallyClassModel::where('parent_id', $data['tally_class_id'])->get()->toArray();

                if(!empty($getTallyClass)) {
                    foreach($getTallyClass as $value) {
                        $tallyClassId[] = $value['id'];
                    }
                }
            }
            else {
                $tallyClassId[] = $data['tally_class_id'];
            }

            $totalInfo->whereIn('tally_class_id', $tallyClassId);

            $incomeList->whereIn('tally_class_id', $tallyClassId);
        }


        $totalInfo = $totalInfo->groupBy('main_id')->first();

        $result['total_money'] = empty($totalInfo)?0:$totalInfo->money;

        $result['income_list'] = $incomeList->orderBy('money', 'desc')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);

        return $this->success($result);
    }

    /**
     * 收入
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/6 16:07
     * @return \Illuminate\Http\JsonResponse
     */
    public function incomeOrExpend1(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
            'type' =>[
                'required',
                Rule::In([0,1]),
            ],//收支类型：0-收入 1-支出
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：'.date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：'.date('Y-m-d'),
            'type.required' => '`报表类型`缺失',
            'type.in' => '`报表类型`错误',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        $condition = [];

        if(!empty($startTime) && !empty($endTime)) {
            $condition[] = ['add_time', '>=', $startTime];
            $condition[] = ['add_time', '<=', $endTime];
        }
        else if(!empty($startTime) && empty($endTime)) {
            $condition[] = ['add_time', '>=', $startTime];
        }
        else if(empty($startTime) && !empty($endTime)) {
            $condition[] = ['add_time', '<=', $endTime];
        }

        $condition['type'] = ['EQ' => $data['type']];

        $condition['main_id'] = ['EQ' => $this->getMainUserId()];

        $tallyClassId = [];
        if(isset($data['tally_class_id'])) {
            $tallyClassInfo = TallyClassModel::where('id', $data['tally_class_id'])->first();

            if($tallyClassInfo['parent_id'] == 0) {
                //获取二级几张类型信息
                $getTallyClass = TallyClassModel::where('parent_id', $data['tally_class_id'])->get()->toArray();

                if(!empty($getTallyClass)) {
                    foreach($getTallyClass as $value) {
                        $tallyClassId[] = $value['id'];
                    }
                }
            }
            else {
                $tallyClassId[] = $data['tally_class_id'];
            }
        }

        $totalInfo = TallyModel::selectRaw(
            'SUM(money) as money'
        )->where($condition);
            if(!empty($tallyClassId)) {
                $totalInfo->whereIn('tally_class_id', $tallyClassId);
            }
        $totalInfo = $totalInfo->groupBy('main_id')->first();

        $result['total_money'] = empty($totalInfo)?0:$totalInfo->money;
        $incomeList = TallyModel::selectRaw(
            'add_time,money,tally_class_name'
        )->where($condition);
        if(!empty($tallyClassId)) {
            $incomeList->whereIn('tally_class_id', $tallyClassId);
        }
        $result['income_list'] = $incomeList->orderBy('money', 'desc')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);

        return $this->success($result);
    }

    /**
     * 采购报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/7 19:57
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementMateriel(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：'.date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：'.date('Y-m-d'),
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        $condition = [];

        if(!empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.purchase_time', '>=', $startTime];
            $condition[] = ['a.purchase_time', '<=', $endTime];
        }
        else if(!empty($startTime) && empty($endTime)) {
            $condition[] = ['a.purchase_time', '>=', $startTime];
        }
        else if(empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.purchase_time', '<=', $endTime];
        }

        $userInfo = [];
        if($this->getMainUserId() == $this->getUserId()) {
            $userInfo['a.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $userInfo['a.user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(
            StatisticsService::statementMateriel($condition, $data, $userInfo)
        );
    }

    /**
     * 采购报表详情
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/7 19:59
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementMaterielDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type_id' =>'required|integer',//商品id
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'type_id.required' => '`商品id`缺失',
            'type_id.integer' => '`商品id`只能为数字',
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
        ]);

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        $condition = [];

        if(!empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.purchase_time', '>=', $startTime];
            $condition[] = ['a.purchase_time', '<=', $endTime];
        }
        else if(!empty($startTime) && empty($endTime)) {
            $condition[] = ['a.purchase_time', '>=', $startTime];
        }
        else if(empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.purchase_time', '<=', $endTime];
        }

        if($this->getMainUserId() == $this->getUserId()) {
            $condition['b.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $condition['b.user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(
            StatisticsService::statementMaterielDetail($data, $condition)
        );
    }

    /**
     * 成本报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/8 14:57
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementCost(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
            'type' =>[
                'required',
                Rule::In([0,1]),//成本报表类型:0:商品;1:套餐;
            ],
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：'.date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：'.date('Y-m-d'),
            'type.required' => '请选择报表类型',
            'type.in' => '报表类型错误',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        $condition = [];

        if($this->getMainUserId() == $this->getUserId()) {
            $condition['a.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $condition['a.user_id'] = ['EQ' => $this->getUserId()];
        }

        if(!empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.out_storage_time', '>=', $startTime];
            $condition[] = ['a.out_storage_time', '<=', $endTime];
        }
        else if(!empty($startTime) && empty($endTime)) {
            $condition[] = ['a.out_storage_time', '>=', $startTime];
        }
        else if(empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.out_storage_time', '<=', $endTime];
        }

        return $this->success(
            StatisticsService::statementCost($condition, $data)
        );
    }

    /**
     * 销售报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/13 13:43
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementSell(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：'.date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：'.date('Y-m-d'),
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        $condition = [];

        if(!empty($startTime) && !empty($endTime)) {
            $condition[] = ['sell_date', '>=', $startTime];
            $condition[] = ['sell_date', '<=', $endTime];
        }
        else if(!empty($startTime) && empty($endTime)) {
            $condition[] = ['sell_date', '>=', $startTime];
        }
        else if(empty($startTime) && !empty($endTime)) {
            $condition[] = ['sell_date', '<=', $endTime];
        }

        if($this->getMainUserId() == $this->getUserId()) {
            $condition['main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $condition['user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(
            StatisticsService::statementSell($condition, $data)
        );
    }

    /**
     * 仓库报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/13 16:36
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementStorage(Request $request)
    {
        $condition['a.main_id'] = ['EQ' => $this->getMainUserId()];

        return $this->success(
            StatisticsService::statementStorage($condition)
        );
    }

    /**
     * 仓库报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/13 16:36
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementStorageDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'storage_id.required' => '`仓库id`缺失',
            'storage_id.integer' => '`仓库id`只能为数字',
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();

        return $this->success(
            StatisticsService::statementStorageDetail($request->storage_id, $data)
        );
    }

    /**
     * 客户报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/15 14:02
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function statementCustomer(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if($this->getMainUserId() == $this->getUserId()) {
            $condition['main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $condition['user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(
            StatisticsService::statementCustomer($data, $condition)
        );
    }

    /**
     * 客户报表详细
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/15 14:33
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementCustomerDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
            'customer_id' => 'required|integer',//供应商或客户id
            'customer_name' => 'required',//供应商或客户id
            'type' =>[
                'required',
                Rule::In([0,1]),
            ],//统计类型;0:采购;1:销售;
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'customer_id.required' => '`供应商或客户id`缺失',
            'customer_id.integer' => '`供应商或客户id`只能为数字',
            'customer_name.required' => '`供应商或客户名称`缺失',
            'type.required' => '`统计类型`缺失',
            'type.In' => '`统计类型`不合法',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if($this->getMainUserId() == $this->getUserId()) {
            $condition['main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $condition['user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(
            StatisticsService::statementCustomerDetail($data, $condition)
        );
    }

    /**
     * 采购商品统计
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2022/8/25 16:50
     * @return \Illuminate\Http\JsonResponse
     */
    public function statisticsPurchasedGoods(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
            'customer_id' => 'required|integer',//供应商或客户id
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：'.date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：'.date('Y-m-d'),
            'customer_id.required' => '`供应商或客户id`缺失',
            'customer_id.integer' => '`供应商或客户id`只能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        $condition = [];

        if(!empty($startTime) && !empty($endTime)) {
            $condition[] = ['b.purchase_time', '>=', $startTime];
            $condition[] = ['b.purchase_time', '<=', $endTime];
        }
        else if(!empty($startTime) && empty($endTime)) {
            $condition[] = ['b.purchase_time', '>=', $startTime];
        }
        else if(empty($startTime) && !empty($endTime)) {
            $condition[] = ['b.purchase_time', '<=', $endTime];
        }

        if($this->getMainUserId() == $this->getUserId()) {
            $condition['b.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $condition['b.user_id'] = ['EQ' => $this->getUserId()];
        }
        $keyword = empty($request->keyword)?'':$request->keyword;
        $list=StatisticsService::statisticsPurchasedGoods($condition, $data,$keyword);
        $this->log('采购商品统计', $list);
        return $this->success($list);
    }

    /**
     * 已售商品统计
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2022/8/26 10:32
     * @return \Illuminate\Http\JsonResponse
     */
    public function statisticsGoodsSold(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
            'customer_id' => 'required|integer',//供应商或客户id
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：'.date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：'.date('Y-m-d'),
            'customer_id.required' => '`供应商或客户id`缺失',
            'customer_id.integer' => '`供应商或客户id`只能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        $condition = [];

      $condition['a.main_id'] = ['EQ' => $this->getMainUserId()];

        if(!empty($startTime) && !empty($endTime)) {
            $condition[] = ['sell_date', '>=', $startTime];
            $condition[] = ['sell_date', '<=', $endTime];
        }
        else if(!empty($startTime) && empty($endTime)) {
            $condition[] = ['sell_date', '>=', $startTime];
        }
        else if(empty($startTime) && !empty($endTime)) {
            $condition[] = ['sell_date', '<=', $endTime];
        }

        $keyword = empty($request->keyword)?'':$request->keyword;
        $list=StatisticsService::sellGoodsList($condition, $data,$keyword);
        $this->log('采购商品统计', $list);
        return $this->success($list);
    }

    /**
     * 进货
     * change 在 2021/11/11 16:36 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function stock(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type' =>'required|integer',//时间 1-今日 2-本月 3-本季
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $condition[] = ['main_id','=',$this->getMainUserId()];

        if($data['type']==1){
            $date = TimeUtil::convertDateSignToUnix();
        }elseif($data['type']==2){
            $date = TimeUtil::convertDateSignToUnix('month');
        }elseif($data['type']==3){
            $date = $this->quarter();
        }
        $tallyModel = MaterielContentModel::select(DB::raw("sum(num) as num,sum(unit_price*num) as total_price"))
            ->from('materiel_content as a')
            ->leftJoin('materiel as b','a.materiel_id', '=','b.id')
            ->where('a.main_id',$this->getMainUserId())
            ->where('in_storage_status',2)
            ->whereBetween('a.purchase_time',$date)
            ->groupBy('materiel_name','type_name')->get();
        $totalMoney = 0;
        $totalNum = 0;
        foreach ($tallyModel as $value){
            $totalMoney+=$value['total_price'];
            $totalNum += $value['num'];
        }
        $modelData['data'] = MaterielContentModel::select(DB::raw("sum(num) as num,materiel_img,materiel_name,type_name,materiel_no,sum(unit_price*num) as total_price"))
            ->from('materiel_content as a')
            ->leftJoin('materiel as b','a.materiel_id', '=','b.id')
            ->where('a.main_id',$this->getMainUserId())
            ->where('in_storage_status',2)
            ->whereBetween('a.purchase_time',$date)
            ->groupBy('materiel_name','type_name')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
        $modelData['total_num'] = $totalNum;
        $modelData['total_money'] = $totalMoney;//总销售额
        return $this->success($modelData);
    }

    /**
     *数据预览
     * Author: zlf
     * Created at 2023/2/28 10:27
     * @param Request $request
     * @return void
     */
    public function dataPreview(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type' =>'required|integer',//时间 1-今日 2-本月 3-本季

        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $condition['main_id'] = $this->getMainUserId();

        if($data['type']==1){
            $date = TimeUtil::convertDateSignToUnix();
        }elseif($data['type']==2){
            $date = TimeUtil::convertDateSignToUnix('month');
        }elseif($data['type']==3){
            $date[0] = strtotime(date('Y').'-01-01 00:00:00');
            $date[1] = time();
        }
        $todayData = [];
        $res = LogOutstorageModel::getTodaySellMoney($condition, $date[0], $date[1]);//今日销售金额和总利润

        $todayData['in_storage_count'] = LogInstorageModel::getTodayInCount($condition, $date[0], $date[1]);//今日入库总数
        $todayData['out_storage_count'] = LogOutStorageModel::getTodayOutCount($condition, $date[0], $date[1]);//今日出库
        $todayData['package_count'] = LogPackageModel::getTodayPackageCount($condition, $date[0], $date[1]);//今日套餐出库总数
        $todayData['trans_storage_count'] = LogOutstorageModel::getTodayAllocateCount($condition, $date[0], $date[1]);//今日调拨数量
        $todayData['storage_warning_count'] = StorageManageModel::getTodayStorageWanringCount($condition, $date[0], $date[1]);//今日预警数量
        $todayData['sell_money'] = empty($res['total_sell_price'])?0:$res['total_sell_price'];//今日销售金额
        $todayData['tally_income'] = TallyModel::getTodayTallyImcomeDelSellData($condition, 0,$date[0], $date[1]);//今日账单收入
        $todayData['total_income_money'] = $todayData['sell_money']+TallyModel::getTodayTallyImcomeDelSellData($condition, 0,$date[0], $date[1]);
        ;//今日总收入
        $todayData['materiel_money'] = MaterielContentModel::getTodayMaterielMoney($condition, $date[0], $date[1]);//今日采购金额
        $todayData['tally_expend'] = TallyModel::getTodayTallyImcomeDelPurchaseData($condition, 1,$date[0], $date[1]);//今日账单支出
        $todayData['total_expend_money'] = $todayData['materiel_money']+TallyModel::getTodayTallyImcomeDelPurchaseData($condition, 1,$date[0], $date[1]);//今日总支出
        $todayData['total_income'] = empty($res['total_income'])?0:$res['total_income'];//今日总利润
        $todayData['total_debt'] = SellModel::getTodaySellMoney($condition, $date[0], $date[1]);//今日总欠款
        $todayData['add_customer'] = SupplierCustomerModel::getTodayAddCustomer($condition, $date[0], $date[1]);//今日新增客户
        $todayData['sell_count'] = SellModel::getTodaySellCount($condition, $date[0], $date[1]);//今日销售单量
        $todayData['materiel_count'] = MaterielModel::getTodayMaterielCount($condition, $date[0], $date[1]);//今日采购数量
        $todayData['return_count'] = SalesReturnModel::getTodayReturnCount($condition, $date[0], $date[1]);//今日退货数量
        $todayData['breakage_count'] =OverflowBreakageModel::getTodaybreakageCount($condition, 1,$date[0], $date[1]);//今日报损数量
        $todayData['overflow_count'] =OverflowBreakageModel::getTodaybreakageCount($condition, 0,$date[0], $date[1]);//今日报溢数量
        $todayData['tally_count'] =TallyModel::getTodayTallyCount($condition, $date[0], $date[1]);//今日记账数量
        $todayData['product_order_count'] =ProductOrderModel::getTodayProductOrderCount($condition,0, $date[0], $date[1]);//今日生产任务数量
        $todayData['finish_product_order_count'] =ProductOrderModel::getTodayProductOrderCount($condition, 2,$date[0], $date[1]);//今日生产(已完成)
        $todayData['unfinished_product_order_count'] =ProductOrderModel::getTodayProductOrderCount($condition, 1,$date[0], $date[1]);//今日生产(未完成)
        $todayData['express_query_count'] =ExpressModel::getQqueryExpressCount($condition, $date[0], $date[1]);//快递查询
        $todayData['browse_album_count'] =0;//浏览画册
        return response()->json(['code'=>0,'msg'=>'success','data'=>$todayData]);
    }
}
